package binarytree;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/20 0:04
 * https://leetcode-cn.com/problems/balanced-binary-tree/
 */
public class IsBalanced {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftDepth = treeHigh(root.left);
        int rightDepth = treeHigh(root.right);
        if (Math.abs(leftDepth - rightDepth) > 1 || leftDepth == -1 || rightDepth == -1) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 求二叉树的高度（从低向上），层次遍历求深度（从高向下）
     * 此方法通用高度和深度
     * @param root
     * @return
     */
    public int treeHigh(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = treeHigh(root.left);
        if (left == -1) {
            return -1;
        }
        int right = treeHigh(root.right);
        if (right == -1) {
            return -1;
        }
        return Math.abs(left - right) <= 1 ? Math.max(left, right) + 1 : -1;
    }

    public static void main(String[] args) {

    }
}
